package com.yjps.web;

import com.yjps.model.SystemContext;
import com.yjps.model.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by pcc on 2015/7/11.
 */
public class SystemContextFilter implements Filter {
    private int pageSize;
    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {
        try {
            System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>2");
            int tps = pageSize;
            try {
                tps = Integer.parseInt(req.getParameter("pageSize"));
            } catch (NumberFormatException e) {}
            int pageOffset = 0;
            try {
                pageOffset = Integer.parseInt(req.getParameter("pager.offset"));
            } catch (NumberFormatException e) {}
            HttpServletRequest hreq = (HttpServletRequest)req;
            SystemContext.setPageOffset(pageOffset);
            SystemContext.setPageSize(tps);
            String realPath = hreq.getSession().getServletContext().getRealPath("");
            realPath = "E:\\2015summer_holiday\\my_document\\web";
            SystemContext.setRealPath(realPath);
            User loginUser = (User)hreq.getSession().getAttribute("loginUser");
            if(loginUser!=null) SystemContext.setLoginUser(loginUser);
            chain.doFilter(req, resp);
        } finally {
            SystemContext.removePageOffset();
            SystemContext.removePageSize();
            SystemContext.removeLoginUser();
            SystemContext.removeRealPath();
        }
    }

    @Override
    public void init(FilterConfig cfg) throws ServletException {
        pageSize = Integer.parseInt(cfg.getInitParameter("pageSize"));
    }
}
